/**
 * ********************************************************
 */
/* Name: Stephen Wiens
 /* Student No.: 00324854
 /* Course: CPSC559
 /* SB DropBox
 *Reason: Main Screen for DropBox
 * 
 /***********************************************************/
package Client;

import SBLib.Clientcheck;
import SBLib.File;
import SBLib.JsonFile;
import SBLib.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
/**
 *
 * @author StephenWiens
 */
public class SB_DropBox extends javax.swing.JFrame {

    static User temp = new User(null, null);
    static ObjectOutputStream outToServer;
    static ObjectInputStream inFromServer;
    static String divider = "&&&";
    static String chunks[];
    static Socket clientSocket;

    /**
     * Creates new form SB_DropBox
     */
    public SB_DropBox() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenu1 = new javax.swing.JMenu();
        jPanel1 = new javax.swing.JPanel();
        list1 = new java.awt.List();
        jLabel3 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        NewTextMenuItem = new javax.swing.JMenuItem();
        UpdateDirectoryMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        EDITMenuItem = new javax.swing.JMenuItem();
        RenameItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();

        jMenu1.setText("jMenu1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        ArrayList<File> TextFiles;

        //           outToServer.writeObject("GET_LISTING");
        TextFiles = JsonFile.JsonTextToFileList((Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"GET_LISTING")).split("&&&")[0]);
        list1.removeAll();
        if (!TextFiles.isEmpty()) {
            int i = TextFiles.size();
            System.out.println(i);
            while(i>0)
            {
                i--;
                list1.add(TextFiles.get(i).getFileName().toString());
            }
        }
        list1.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
        list1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                list1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(list1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(list1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 266, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(0, 0, 204));
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel3.setText("SB DROPBOX");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Client/Dropbox-project.png"))); // NOI18N

        jLabel2.setText("       ");
        jLabel2.setText("User: "+temp.getUserName()+"\n IP Address: "+clientSocket.getInetAddress().getHostAddress());

        fileMenu.setMnemonic('f');
        fileMenu.setText("File");

        NewTextMenuItem.setMnemonic('a');
        NewTextMenuItem.setText("New Text File");
        NewTextMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                NewTextMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(NewTextMenuItem);

        UpdateDirectoryMenuItem.setMnemonic('o');
        UpdateDirectoryMenuItem.setText("Update Directory");
        UpdateDirectoryMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UpdateDirectoryMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(UpdateDirectoryMenuItem);

        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setMnemonic('e');
        editMenu.setText("Edit");

        EDITMenuItem.setMnemonic('t');
        EDITMenuItem.setText("Edit text");
        EDITMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EDITMenuItemActionPerformed(evt);
            }
        });
        editMenu.add(EDITMenuItem);

        RenameItem.setText("Rename");
        RenameItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RenameItemActionPerformed(evt);
            }
        });
        editMenu.add(RenameItem);

        deleteMenuItem.setMnemonic('d');
        deleteMenuItem.setText("Delete");
        deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteMenuItemActionPerformed(evt);
            }
        });
        editMenu.add(deleteMenuItem);

        menuBar.add(editMenu);

        setJMenuBar(menuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(0, 67, Short.MAX_VALUE)
                                .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 235, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .add(layout.createSequentialGroup()
                                .add(23, 23, 23)
                                .add(jLabel2)
                                .add(0, 0, Short.MAX_VALUE)))
                        .add(18, 18, 18)
                        .add(jLabel1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 116, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(2, 2, 2)
                        .add(jLabel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 36, Short.MAX_VALUE)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void UpdateDirectoryMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpdateDirectoryMenuItemActionPerformed
        //Ask the server to get a directory listing
        ArrayList<File> TextFiles;
           // outToServer.writeObject("GET_LISTING");
            TextFiles = JsonFile.JsonTextToFileList((Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"GET_LISTING")).split(divider)[0]);
            list1.removeAll();
            //fill in the list with the current documents that are able to to be viewed.
            if (!TextFiles.isEmpty()) {
                int i = TextFiles.size();
                System.out.println(i);
                while (i > 0) {
                    i--;
                    list1.add(TextFiles.get(i).getFileName().toString());
                }
            }

    }//GEN-LAST:event_UpdateDirectoryMenuItemActionPerformed

    private void NewTextMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewTextMenuItemActionPerformed
        //Create a new document
        File_viewer.main(temp, outToServer, inFromServer, 0, null, null,clientSocket);
    }//GEN-LAST:event_NewTextMenuItemActionPerformed

    private void list1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_list1ActionPerformed

            //View the current selected document, double clicked
            //outToServer.writeObject("VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName());
            chunks = Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName()).split(divider);
            File_viewer.main(temp, outToServer, inFromServer, 1, chunks[1], list1.getSelectedItem(),clientSocket);

    }//GEN-LAST:event_list1ActionPerformed

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
    }//GEN-LAST:event_formMouseMoved

    private void RenameItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RenameItemActionPerformed

            //Rename the current selected item. 
            //View is called so it can display all the information of the file to the user first
            //outToServer.writeObject("VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName());
            chunks = Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName()).split(divider);
            File_viewer.main(temp, outToServer, inFromServer, 2, chunks[1], list1.getSelectedItem(),clientSocket);

    }//GEN-LAST:event_RenameItemActionPerformed

    private void formMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMousePressed
        ArrayList<File> TextFiles;
        //Update the current list.
            //outToServer.writeObject("GET_LISTING");
            TextFiles = JsonFile.JsonTextToFileList((Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"GET_LISTING")).split("&&&")[0]);
            list1.removeAll();
            if (!TextFiles.isEmpty()) {
                int i = TextFiles.size();
                System.out.println(i);
                while (i > 0) {
                    i--;
                    list1.add(TextFiles.get(i).getFileName().toString());
                }
            }
    }//GEN-LAST:event_formMousePressed

    private void EDITMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EDITMenuItemActionPerformed
            //Edit the message area. 
            //View is called so the user can see the current message.
            //outToServer.writeObject("VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName());
            chunks = Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName()).split(divider);
            File_viewer.main(temp, outToServer, inFromServer, 3, chunks[1], list1.getSelectedItem(),clientSocket);
    }//GEN-LAST:event_EDITMenuItemActionPerformed

    private void deleteMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteMenuItemActionPerformed

            //Delete the current message selected.
            //view is called so the user can see what they are about to delete
            //outToServer.writeObject("VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName());
            chunks = Clientcheck.connectionvalid(clientSocket,temp,inFromServer,outToServer,"VIEW" + divider + list1.getSelectedItem() + divider + temp.getUserName()).split(divider);
            File_viewer.main(temp, outToServer, inFromServer, 4, chunks[1], list1.getSelectedItem(),clientSocket); 
    }//GEN-LAST:event_deleteMenuItemActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(final User temp1, final ObjectOutputStream outToServer1, final ObjectInputStream inFromServer1, final Socket clientSocket1) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SB_DropBox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SB_DropBox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SB_DropBox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SB_DropBox.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                temp = temp1;
                outToServer = outToServer1;
                inFromServer = inFromServer1;
                clientSocket = clientSocket1;
                new SB_DropBox().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem EDITMenuItem;
    private javax.swing.JMenuItem NewTextMenuItem;
    private javax.swing.JMenuItem RenameItem;
    private javax.swing.JMenuItem UpdateDirectoryMenuItem;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JPanel jPanel1;
    private java.awt.List list1;
    private javax.swing.JMenuBar menuBar;
    // End of variables declaration//GEN-END:variables
}
